//
//  BrowserView.m
//  iCodeMacRun
//
//  Created by Andrew Barry on 1/08/09.
//  Copyright 2009 Barry Computer Services. All rights reserved.
//

#import "BrowserView.h"

@implementation BrowserView

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }
    return self;
}

-(void) setObject: (jsvalue)o withTarget: (jsvalue) targ withContext: (jscontext *) cx {
	jsaddroot(cx, &obj);
	jsaddroot(cx, &target);
	obj = o;
	target = targ;
	_cx = cx;
}

- (void)browser:(NSBrowser *)sender willDisplayCell:(id)cell atRow:(NSInteger)row column:(NSInteger)column {
	NSBrowserCell *bcell = cell;
	
	NSString *path = [self pathToColumn:column];
	
	jscontext *cx = _cx;
	
	jsvalue oldEvent = JSVAL_VOID;
	jsaddroot(_cx, &oldEvent);
	oldEvent = _cx->slots[GLOBAL_EVENT];
	_cx->slots[GLOBAL_EVENT] = jsnewobject(_cx);
	jsset(cx, cx->slots[GLOBAL_EVENT], 0, "path", jsstrFromNSString(cx, path));
	jsset(cx, cx->slots[GLOBAL_EVENT], 0, "row", jsnumi(cx, row));
	
	jsvalue rv = jsinvokename(cx, obj, "_Row", nil, 0);
	cx->slots[GLOBAL_EVENT] = oldEvent;
	jsremoveroot(_cx, &oldEvent);
	
	jsaddroot(_cx, &rv);
	
	[bcell setStringValue:jsgetstring(cx, rv, 0, "text", @"")];
	[bcell setLeaf:jsgetbool(cx, rv, 0, "leaf", YES)];

	jsvalue v = jsget(cx, rv, 0, "image");
	if (v && v != JSVAL_NULL) {
		NSImage *img = idFromObject(cx, v);
		[bcell setImage: img];
	}
	
	jsremoveroot(cx, &rv);
}

- (NSInteger)browser:(NSBrowser *)sender numberOfRowsInColumn:(NSInteger)column {
	NSString *path = [self pathToColumn:column];
	
	jscontext *cx = _cx;

	jsvalue oldEvent = JSVAL_VOID;
	jsaddroot(_cx, &oldEvent);
	oldEvent = _cx->slots[GLOBAL_EVENT];
	_cx->slots[GLOBAL_EVENT] = jsnewobject(_cx);
	jsset(cx, cx->slots[GLOBAL_EVENT], 0, "path", jsstrFromNSString(cx, path));

	jsvalue rv = jsinvokename(cx, obj, "_RowCount", nil, 0);
	
	cx->slots[GLOBAL_EVENT] = oldEvent;
	jsremoveroot(_cx, &oldEvent);

	return jsasint(cx, rv);
}

-(void)browserAwake {
	[self setHasHorizontalScroller:YES];
	[self setTitled:NO];
	[self setDelegate: self];
}

@end
